package com.qf.controller;

import com.qf.util.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.security.krb5.internal.PAData;

/*
 *@Description:
 *@author:刘哥
 *@Date:17:51 2022/7/19
 */
//获取前端数据，和注明controller层
@RestController
public class UserController {
//    登录操作表单是post请求
    @PostMapping("/doLogin")
    public Result login(String username, String password,Boolean rememberMe){
//        System.out.println("username = " + username);
//        System.out.println("password = " + password);
        System.out.println("rememberMe = " + rememberMe);
//        通过SecurityUtils工具类获取Subject对象(Subject对象里面包含登录操作)
        Subject subject = SecurityUtils.getSubject();

//        判断(防止空指针异常)
        if (password == null) {
            password="";
        }
        if (rememberMe == null) {
            rememberMe=false;
        }
//        数据库密码是加密的,前端密码也得加密进行比较
        Md5Hash md5Hash=new Md5Hash(password,username,1024);
//     创建token  接收前端账户和密码信息
        UsernamePasswordToken token = new UsernamePasswordToken(username,md5Hash.toString(),rememberMe);

//        登录
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("未知账户异常");
            return Result.error();
        }  catch (LockedAccountException e) {
            e.printStackTrace();
            System.out.println("账户已锁定");
        }catch (CredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误");
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }
//        System.out.println(subject.isAuthenticated()?"登录成功":"登录失败");
        System.out.println(subject.hasRole("管理员")?"是管理员":"不是管理员");
        System.out.println(subject.isPermitted("sys:user:add")?"有添加用户的权限":"没有添加用户的权限");
      return Result.ok();

    }
    @RequestMapping("/logout")
    public Result loginOut(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();

        return Result.ok();
    }
}
